package cn.com.taiji.oospub.wechat.controller.weekmeu;

import cn.com.taiji.common.model.finals.SessionNames;
import cn.com.taiji.common.pub.StringTools;
import cn.com.taiji.oospub.wechat.common.Finals;
import cn.com.taiji.oospub.wechat.common.tool.DoubleTools;
import cn.com.taiji.oospub.wechat.controller.BaseLogController;
import cn.com.taiji.oospub.wechat.entity.*;
import cn.com.taiji.oospub.wechat.service.*;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.SimplePropertyPreFilter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 周菜单控制器
 */
@Controller
@RequestMapping("/wx/weekMenu")
public class WeekMenuController extends BaseLogController {
    @Autowired
    private IWeekMenuService weekMenuManager;
    @Autowired
    private ISchoolBaseInfoService schoolManager;
    @Autowired
    private ICoursesService coursesManager;
    @Autowired
    private ICourseTypeService courseTypeManager;
    @Autowired
    private IRestaurantService restaurantService;
    @Autowired
    private ICoursesOrdersDetailsService coursesOrdersDetailsService;
    @Autowired
    private ICourseNutritionService coursesNutritionService;
    @Autowired
    private IMealTimeService mealTimeService;
    @Autowired
    private IMemberBaseInfoService memberBaseInfoService;
    @Autowired
    private ICoursesImgService coursesImgService;
    @Value("${PROJECT_CODE}")
    public String PROJECT_CODE;

    /**
     * 预约外卖查询菜品
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/manage", method = RequestMethod.GET)
    @ResponseBody
    public String manageGet(Model model, HttpServletRequest request, HttpServletResponse response) throws IOException {
        MemberBaseInfo member = (MemberBaseInfo) WebUtils.getSessionAttribute(request, SessionNames.LOGIN_USER);
        String restaurantId = request.getParameter("restaurantId");
//        if (!StringUtils.hasText(restaurantId)) {
//            restaurantId = member.getRestaurant().getId();
//        }
        String day_of_week = request.getParameter("DAY_OF_WEEK");
        Boolean isToday = false;
        QueryWrapper<CourseType> queryModel = new QueryWrapper<>();
        queryModel.eq("is_delete", false);
        List<CourseType> listType = courseTypeManager.list(queryModel);
        //周一时间
        LocalDate c = LocalDate.now().with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
        //获取当天时间
        DayOfWeek today = LocalDateTime.now().getDayOfWeek();
        LocalDate c2 = c;
        //------计算本周一时间结束-------
        //菜品图片列表
        List<CoursesImg> coursesImgList = new ArrayList<>();
        //菜品列表
        List<Courses> list = new ArrayList<>();
        //查询条件
        QueryWrapper<Courses> coursesModel = new QueryWrapper<>();
        coursesModel.eq("is_delete", false);
        coursesModel.eq("school_id", member.getSchoolId());
//            coursesModel.eq("restaurant_id", restaurantId);
        coursesModel.in("type", "wm", "dcwm");
        coursesModel.orderByDesc("is_top");
        switch (day_of_week) {
            case "1":
                break;
            case "2":
                c2 = c.plusDays(1);
                break;
            case "3":
                c2 = c.plusDays(2);
                break;
            case "4":
                c2 = c.plusDays(3);
                break;
            case "5":
                c2 = c.plusDays(4);
                break;
            case "6":
                c2 = c.plusDays(5);
                break;
            case "7":
                c2 = c.plusDays(6);
                break;
        }
        coursesModel.ge("startTime", c2);
        coursesModel.lt("endTime", LocalDateTime.of(c2, LocalTime.MAX));
        list = coursesManager.list(coursesModel);
        if (list != null && list.size() > 0) {
            for (Courses courses : list) {
                coursesImgList = coursesImgService.query()
                        .eq("course_pos_no", courses.getPosNo())
                        .isNotNull("img_path")
                        .isNotNull("img_url")
                        .ge("last_changed_time",LocalDate.now().minusDays(1))
                        .orderByDesc("mainImg").list();
                if (coursesImgList != null && coursesImgList.size() > 0) {
                    courses.setImageMainPath(coursesImgList.get(0).getImgUrl());
                }
                courses.setCnList(coursesNutritionService.query()
                        .eq("is_delete", false)
                        .eq("recipes_code", courses.getPosNo())
                        .in("nutrition_id", 4, 13, 7, 5, 6, 2).list());
                if (null != courses.getCnList() && courses.getCnList().size() > 0) {
                    for (CourseNutrition courseNutrition : courses.getCnList()) {
                        //营养标签
                        if ("dz.png".equals(courseNutrition.getTagLogo())) {
                            courses.setDzLogo("dz.png");
                        } else if ("dk.png".equals(courseNutrition.getTagLogo())) {
                            courses.setDkLogo("dk.png");
                        } else if ("dy.png".equals(courseNutrition.getTagLogo())) {
                            courses.setDyLogo("dy.png");
                        } else if ("gw.png".equals(courseNutrition.getTagLogo())) {
                            courses.setGwLogo("gw.png");
                        }
                    }
                }
            }
        }
        for (CourseType courseType : listType) {
            courseType.setWeekList(list.stream().filter(i -> i.getCoursesTypeId().equals(courseType.getId())).collect(Collectors.toList()));
        }
        //查询推荐
        model.addAttribute("tjList", list.stream().filter(i -> "1".equals(i.getIsTop())).collect(Collectors.toList()));
        //查询购物车
        QueryWrapper<CoursesOrdersDetails> detailModel = new QueryWrapper<>();
        detailModel.eq("is_effective", false);
        detailModel.eq("creator", member.getId());
        detailModel.in("lb", "wm", "dcwm");
        //仅查询当天下单订单
        detailModel.ge("last_changed", LocalDate.now());
        List<CoursesOrdersDetails> lsList = coursesOrdersDetailsService.queryList(detailModel);

        ArrayList<CoursesOrdersDetails> gwcList = new ArrayList<>();

        Courses courses = new Courses();

        MealTime mealTime=new MealTime();

        LocalTime nowTime = LocalTime.now();
        if (lsList != null && lsList.size() > 0) {
            for (CoursesOrdersDetails coursesOrdersDetails : lsList) {
                courses = coursesOrdersDetails.getCourse();
                QueryWrapper<MealTime> mealTimeWrapper = new QueryWrapper<>();
                mealTimeWrapper.eq("code", courses.getMealTimeCode());
                mealTimeWrapper.eq("mealType", courses.getType());
                mealTimeWrapper.eq("school_id", member.getSchoolId());
                mealTime = mealTimeService.getOne(mealTimeWrapper, false);
                if (courses.getEndTime().isBefore(LocalDateTime.now().plusDays(1))) {
                    if (/*mealTime.getDCstartTime().toLocalTime().isAfter(nowTime) || */mealTime.getDCendTime().toLocalTime().isBefore(nowTime)) {
                        continue;
                    }
                }
                coursesOrdersDetails.setTotalPrice(coursesOrdersDetails.getPrice() * coursesOrdersDetails.getQuantity());
                if (coursesOrdersDetails.getRemark() != null && !"".equals(coursesOrdersDetails.getRemark())) {
                    coursesOrdersDetails.setCourseName(courses.getNameCh() + "(" + coursesOrdersDetails.getRemark() + ")");
                    coursesOrdersDetails.setCourseNameEn(courses.getNameEn() + "(" + coursesOrdersDetails.getRemark() + ")");
                } else {
                    coursesOrdersDetails.setCourseName(courses.getNameCh());
                    coursesOrdersDetails.setCourseNameEn(courses.getNameEn());
                }
                for (Courses course : list) {
                    if (course.getId().equals(coursesOrdersDetails.getCourseId())) {
                        course.setNum(course.getNum() + coursesOrdersDetails.getQuantity().intValue());
                        break;
                    }
                }
                gwcList.add(coursesOrdersDetails);
            }
        }
        model.addAttribute("nutrient", getNutrient(gwcList, member));
        model.addAttribute("orerDeatailList", gwcList);
        model.addAttribute("CoursesType", listType.stream().filter(i -> i.getWeekList() != null && i.getWeekList().size() > 0).collect(Collectors.toList()));
        return JSONObject.toJSONString(model, SerializerFeature.DisableCircularReferenceDetect);
    }

    //获取营养信息
    private Map<String, Double> getNutrient(List<CoursesOrdersDetails> detailList, MemberBaseInfo member) {
        Map<String, Double> map = new HashMap<>();
        for (CoursesOrdersDetails coursesOrdersDetails : detailList) {
            List<CourseNutrition> courseNutrition = coursesNutritionService.query()
                    .eq("recipes_code", coursesOrdersDetails.getCourse().getPosNo())
                    .eq("is_delete", false).list();
            for (CourseNutrition courseNutrition2 : courseNutrition) {
                if (map.containsKey(courseNutrition2.getNutritionCode())) {
                    Double temVal = map.get(courseNutrition2.getNutritionCode());
                    temVal += courseNutrition2.getQuantity() * coursesOrdersDetails.getQuantity();
                    map.put(courseNutrition2.getNutritionCode(), temVal);
                } else {
                    Double val = courseNutrition2.getQuantity() * coursesOrdersDetails.getQuantity();
                    map.put(courseNutrition2.getNutritionCode(), val);
                }
            }
        }
        HashMap<String, Double> hashMap = new HashMap<>();
        if (Finals.ZhOrEn.Z.equals(member.getZhOrEn())) {
            for (String key : map.keySet()) {
                if (Finals.NUT_CODE_NL.equals(key)) {
                    hashMap.put("能量(kcal)", DoubleTools.doubleNumberFormat2(map.get(key)));
                }
                if (Finals.NUT_CODE_TSHHW.equals(key)) {
                    hashMap.put("碳水化物(g)", DoubleTools.doubleNumberFormat2(map.get(key)));
                }
                if (Finals.NUT_CODE_SSXW.equals(key)) {
                    hashMap.put("钠(mg)", DoubleTools.doubleNumberFormat2(map.get(key)));
                }
                if (Finals.NUT_CODE_DBZ.equals(key)) {
                    hashMap.put("蛋白质(g)", DoubleTools.doubleNumberFormat2(map.get(key)));
                }
                if (Finals.NUT_CODE_ZF.equals(key)) {
                    hashMap.put("脂肪(g)", DoubleTools.doubleNumberFormat2(map.get(key)));
                }
            }
        } else {
            for (String key : map.keySet()) {
                if (Finals.NUT_CODE_NL.equals(key)) {
                    hashMap.put("Energy(kcal)", DoubleTools.doubleNumberFormat2(map.get(key)));
                }
                if (Finals.NUT_CODE_TSHHW.equals(key)) {
                    hashMap.put("Carbohydrate(g)", DoubleTools.doubleNumberFormat2(map.get(key)));
                }
                if (Finals.NUT_CODE_SSXW.equals(key)) {
                    hashMap.put("Na(mg)", DoubleTools.doubleNumberFormat2(map.get(key)));
                }
                if (Finals.NUT_CODE_DBZ.equals(key)) {
                    hashMap.put("Protein(g)", DoubleTools.doubleNumberFormat2(map.get(key)));
                }
                if (Finals.NUT_CODE_ZF.equals(key)) {
                    hashMap.put("Fat(g)", DoubleTools.doubleNumberFormat2(map.get(key)));
                }
            }
        }
        return hashMap;
    }

    /**
     * 周菜单
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/manage2", method = RequestMethod.GET)
    @ResponseBody
    public String manage2Get(Model model, HttpServletRequest request, HttpServletResponse response) throws IOException {
        MemberBaseInfo member = (MemberBaseInfo) WebUtils.getSessionAttribute(request, SessionNames.LOGIN_USER);
//        String restaurantId = member.getRestaurant().getId();
        String day_of_week = request.getParameter("DAY_OF_WEEK");
        String meal_time_code = request.getParameter("meal_time_code");
        QueryWrapper<CourseType> queryModel = new QueryWrapper<>();
        queryModel.eq("is_delete", false);
        List<CourseType> listType = courseTypeManager.list(queryModel);
        //周一时间
        LocalDate c = LocalDate.now().with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));

        //获取当天时间
        DayOfWeek today = LocalDateTime.now().getDayOfWeek();
        LocalDate c2 = c;
        //菜品图片列表
        List<CoursesImg> coursesImgList = new ArrayList<>();
        //菜品列表
        List<Courses> list = new ArrayList<>();
        //查询条件
        QueryWrapper<Courses> coursesModel = new QueryWrapper<>();
        coursesModel.eq("is_delete", false);
        coursesModel.eq("school_id", member.getSchoolId());
//            coursesModel.eq("restaurant_id", restaurantId);
        coursesModel.orderByDesc("is_top");
        coursesModel.eq("meal_time_code", meal_time_code);
        switch (day_of_week) {
            case "1":
                break;
            case "2":
                c2 = c.plusDays(1);
                break;
            case "3":
                c2 = c.plusDays(2);
                break;
            case "4":
                c2 = c.plusDays(3);
                break;
            case "5":
                c2 = c.plusDays(4);
                break;
            case "6":
                c2 = c.plusDays(5);
                break;
            case "7":
                c2 = c.plusDays(6);
                break;
        }
        coursesModel.ge("startTime", c2);
        coursesModel.lt("endTime", LocalDateTime.of(c2, LocalTime.MAX));
        list = coursesManager.list(coursesModel);
        for (CourseType courseType : listType) {
            courseType.setWeekList(list.stream().filter(i -> i.getCoursesTypeId().equals(courseType.getId())).collect(Collectors.toList()));
        }
        model.addAttribute("CoursesType", listType.stream().filter(i -> i.getWeekList() != null && i.getWeekList().size() > 0).collect(Collectors.toList()));
        return JSONObject.toJSONString(model);
    }

    /**
     * 查询周菜单(浏览器扫描二维码查看)
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/view", method = RequestMethod.POST)
    @ResponseBody
    public String manage3Get(Model model, HttpServletRequest request, HttpServletResponse response) throws IOException {
        String schoolCode = request.getParameter("code");
//        String restaurantId = request.getParameter("restaurantId");
        SimplePropertyPreFilter filter = new SimplePropertyPreFilter("dkLogo", "dyLogo", "dzLogo", "gwLogo", "imageMainPath", "price", "CoursesType", "weekList", "nameCh", "nameEn", "id", "mealTimeCode", "dayId");
        Object oldModel =WebUtils.getSessionAttribute(request, "model");
        if (oldModel!=null){
            return JSONObject.toJSONString(oldModel, filter);
        }
        if (schoolCode == null) {
            schoolCode = PROJECT_CODE;
        }
        SchoolBaseInfo schoolBaseInfo = schoolManager.findByProperty("Code", PROJECT_CODE);
//        if (restaurantId == null) {
//            restaurantId = restaurantService.findByProperty("school_id", schoolBaseInfo.getId()).getId();
//        }
        //周一时间
        LocalDate monday = LocalDate.now().with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
        //周日时间
        LocalDate sunday = monday.plusDays(6);
        //查询本周菜品
        List<Courses> coursesList = coursesManager.query().eq("school_id", schoolBaseInfo.getId())
//                .eq("restaurant_id", restaurantId)
                .eq("is_delete", "0")
                .ge("startTime", monday)
                .le("endTime", sunday).list();
        //查询菜品分类
        List<CourseType> courseTypes = courseTypeManager.query().eq("is_delete", false).list();
        if (coursesList != null && coursesList.size() > 0) {
            List<CoursesImg> coursesImgList = new ArrayList<>();
            List<CourseNutrition> courseNutritionlist = new ArrayList<>();
            for (Courses courses : coursesList) {
                //查询营养标签
                courseNutritionlist = coursesNutritionService.query()
                        .eq("recipes_code", courses.getPosNo())
                        .eq("is_delete", false).list();
                if (null != courseNutritionlist && courseNutritionlist.size() > 0) {
                    for (CourseNutrition courseNutrition : courseNutritionlist) {
                        //营养标签
                        if ("dz.png".equals(courseNutrition.getTagLogo())) {
                            courses.setDzLogo("dz.png");
                        } else if ("dk.png".equals(courseNutrition.getTagLogo())) {
                            courses.setDkLogo("dk.png");
                        } else if ("dy.png".equals(courseNutrition.getTagLogo())) {
                            courses.setDyLogo("dy.png");
                        } else if ("gw.png".equals(courseNutrition.getTagLogo())) {
                            courses.setGwLogo("gw.png");
                        }
                    }
                }
                //--------查询菜品主图开始----------
                coursesImgList = coursesImgService.query()
                        .eq("course_pos_no", courses.getPosNo())
                        .isNotNull("img_path")
                        .isNotNull("img_url")
                        .orderByDesc("mainImg").list();
//                courses.setCoursesImgList(coursesImgList);
                if (coursesImgList != null && coursesImgList.size() > 0) {
                    courses.setImageMainPath(coursesImgList.get(0).getImgUrl());
                }
//                //--------查询菜品主图结束----------
            }
        }
        for (CourseType courseType : courseTypes) {
            courseType.setWeekList(coursesList.stream().filter(i -> i.getCoursesTypeId().equals(courseType.getId())).collect(Collectors.toList()));
        }
        model.addAttribute("CoursesType", courseTypes.stream().filter(i -> i.getWeekList() != null && i.getWeekList().size() > 0).collect(Collectors.toList()));
        WebUtils.setSessionAttribute(request, "model",model);
        return JSONObject.toJSONString(model, filter);
    }

}





